package routes

import (
	"msems/controller"
	"msems/logger"
	"msems/middlewares"
	"msems/settings"
	"net/http"

	"github.com/onsi/ginkgo/reporters/stenographer/support/go-colorable"

	"github.com/gin-gonic/gin"
)

func Setup(mode string) *gin.Engine {
	//如果模式为发布模式.调用gin的ReleaseMode将不再输出日志到终端
	if mode == "release" {
		gin.SetMode(gin.ReleaseMode)
	}
	// 启用gin的日志输出带颜色
	gin.ForceConsoleColor()
	// 替换默认Writer（关键步骤）
	gin.DefaultWriter = colorable.NewColorableStdout()
	r := gin.New()
	r.Use(logger.GinLogger(), logger.GinRecovery(true), Cors())
	r.GET("/", func(c *gin.Context) {
		c.String(http.StatusOK, settings.Conf.Version)
	})
	v1 := r.Group("api/v1")
	{
		// 后台管理
		admin := v1.Group("admin")
		{
			//注册
			admin.POST("/signup", controller.SignUpHandler)
			//登录
			//登录,登陆成功返回token
			admin.POST("/login", controller.AdminLoginHandler)
			//发送邮箱
			admin.POST("/email", controller.AdminSendEmailHandler)
			//验证验证码且修改密码
			admin.POST("/code", controller.AdminCodeHandler)
			//通过验证码修改密码
			admin.POST("/change_p", controller.AdminChangePHandler)
			//登陆后访问
			admin.Use(middlewares.JWTAuthMiddleware())
			{
				//插入修改删除学院信息
				admin.POST("/change_college", controller.AdminChangeColtHandler)
				//获取所有学院
				admin.GET("/college_all", controller.AdminGetColAllHandler)
				//管理员注册
				admin.POST("/insert_admin", controller.AdminInsertAdminHandler)
			}

		}

	}
	return r
}

// Cors 处理跨域请求,支持options访问
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		method := c.Request.Method
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Headers", "Content-Type,AccessToken,X-CSRF-Token, Authorization, Token")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, PATCH, DELETE")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		// 放行所有OPTIONS方法，因为有的模板是要请求两次的
		if method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}

		// 处理请求
		c.Next()
	}
}
